/*  
 *parser config buffer  
 *eg  
 *  key=value  
 */  
#include <stdio.h>   
#include <stdlib.h>   
#include <string.h>   
#include <ctype.h>
#include <assert.h>   
#include "key_value.h"   
 
#ifdef __cplusplus   
extern "C"  
{   
#endif      
 
static char send_buffer[SEND_BUFFER_LEN] = {0};

//for recv 
bool check_rsp_data_valid(char * rspbuf,int rsplen,char* cmd,int cmdlen,int * parse_len)
{
	assert((NULL != rsplen) && (NULL != cmd) && (0 < rsplen) && (0 < cmdlen));

	if(rsplen != get_elem_len(rspbuf,parse_len))
	{
		return false;
	}

	if(cmdlen != get_elem_len(rspbuf,parse_len))
	{
		return false;
	}

	if(0 != strncmp(cmd,rspbuf+8,cmdlen))
	{
		return false;
	}

	*parse_len += cmdlen;
	return true;
}

void get_parameter(int * parlen, char** par,char * rspbuf,int *parse_len)
{
	char * pmem = NULL;

	assert((NULL != parlen) && (NULL != par) && (NULL != rspbuf) && (NULL != parse_len));

	*parlen = get_elem_len(rspbuf,parse_len);
	assert (0 < *parlen);

	pmem = (char*)malloc(*parlen+1);
	assert(NULL != pmem);
	memset(pmem,0,*parlen+1);
	memcpy(pmem,rspbuf+(*parse_len),*parlen);	
	*par = pmem;
	return;
}

int get_elem_len(char *buffer,int* parse_len)
{
	int ret = 0;
	char buf[5] = {0};

	assert(NULL != buffer);

	memcpy(buf,buffer+*parse_len,4);
	buf[4] = '\0';

	ret = atoi(buf);
	*parse_len = *parse_len+4;
	printf("get_elem_len[%d]\n",ret);

	return ret;
}

//for send 
void send_buffer_init(char ** buffer,int * total_len)
{
	assert((NULL != buffer) && (NULL != total_len));

	memset(send_buffer,0,SEND_BUFFER_LEN);

	*buffer = send_buffer;

	*total_len = 4;

	return;
}

void add_cmd(char *cmd,int cmdlen,char *buffer,int * total_len)
{
	int total = 0;
	char bufbigin[5] = {0};

	assert((NULL != buffer) && (NULL != total_len));
	assert((NULL != cmd) && (0 < cmdlen));

	sprintf(buffer+(*total_len),"%4d",cmdlen);
	*total_len += 4;
	memcpy(buffer+(*total_len),cmd,cmdlen);
	*total_len += cmdlen;

	sprintf(buffer+(*total_len),"%4d",0);
	*total_len += 4;

	sprintf(bufbigin,"%4d",*total_len);
	memcpy(buffer,bufbigin,4);
	return;
}

void add_elem(char *elem,int elemlen,int parabegin,char *buffer,int * total_len)
{
	int total = 0;
	char bufbigin[5] = {0};
	char parabeginbuf[5] = {0};
	int paranum = 0;

	assert((NULL != buffer) && (NULL != total_len));
	assert((NULL != elem) && (0 < elemlen));
	assert(0 < parabegin);

	memcpy(parabeginbuf,buffer+parabegin-4,4);
	paranum = atoi(parabeginbuf);
	paranum++;
	memset(parabeginbuf,0,5);
	sprintf(parabeginbuf,"%4d",paranum);
	memcpy(buffer+parabegin-4,parabeginbuf,4);

	sprintf(buffer+(*total_len),"%4d",elemlen);
	*total_len += 4;
	memcpy(buffer+(*total_len),elem,elemlen);
	*total_len += elemlen;
	sprintf(bufbigin,"%4d",*total_len);
	memcpy(buffer,bufbigin,4);
	return;
}

#ifdef __cplusplus   
}; //end of extern "C" {   
#endif  
